<template>
  <div>
       <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{path:'/home'}">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
      </el-row>
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand"  style="margin:16px;">
          <template slot-scope="scope">
            <div style="margin: 16px">
            <el-row class="vcenter" :class="['bd-bottom',i1==0?'bd-top':'']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)"> {{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row class="vcenter" :class="i2==0?'':'bd-top'" v-for="(item2,i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag closable  @close="removeRightById(scope.row, item2.id)" type="success"> {{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                      <el-tag closable  @close="removeRightById(scope.row, item3.id)" type="warning" v-for="(item3) in item2.children" :key="item3.id"> {{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            </div>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRole(scope.row)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-card>
      <!-- 添加角色对话框 -->
      <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" 
        :close-on-click-modal="false" @close="addDialogClose">
        <el-form ref="addFormRef" :model="addForm" :rules="formRules" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addForm.roleDesc"></el-input>
          </el-form-item>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 修改角色对话框 -->
      <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="50%" 
        :close-on-click-modal="false" >
        <el-form ref="editFormRef" :model="editForm" :rules="formRules" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input :value="editForm.roleName" disabled></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRole">确 定</el-button>
        </div>
      </el-dialog>
       <!-- 分配权限对话框 -->
      <el-dialog title="修改角色" :visible.sync="setRightDialogVisible" width="50%" 
        :close-on-click-modal="false">
        <span>分配权限</span>
        <el-tree :data="rightList" 
          :props="rightListProps" 
          node-key="id" 
          :default-checked-keys="defaultCheckedKeys"
          ref="treeRef"
          show-checkbox default-expand-all>
        </el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRoleRightList">确 定</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [],
      rightList: [],
      addDialogVisible: false,
      editDialogVisible: false,
      setRightDialogVisible: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      editForm: {
        id: '',
        roleName: '',
        roleDesc: ''
      },
      formRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      rightListProps: {
          label: 'authName',
          children: 'children'
      },
      defaultCheckedKeys: [],
      curRoleId: ''
    }
  },
  created() {
    this.getRoleList();
  },
  methods: {
    async getRoleList() {
      const { data: res  } = await this.$http.get('roles');
      if(res.meta.status!=200) {
        return this.$message.error('获取角色列表失败！');
      }
      this.roleList=res.data;
      console.log(res.data);
    },
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    addRole() {
      this.$refs.addFormRef.validate(async (valid)=>{
        if(!valid) return;
        const { data: res } = await this.$http.post('roles', this.addForm);
        if( res.meta.status == 201 )
        {
          this.addDialogVisible=false;
          this.$message.success('添加成功！');
          this.getRoleList();
        }
        else
        {
          this.$message.error('添加失败！');
        }
      });      
    },
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(`roles/${id}`);
      if( res.meta.status == 200 )
        {
          console.log(res.data);
          this.editForm.id=id;
          this.editForm.roleName=res.data.roleName;
          this.editForm.roleDesc=res.data.roleDesc;
          this.editDialogVisible=true;
        }
        else
        {
          this.$message.error('查询角色信息失败！');
        }
    },
    editRole() {
      this.$refs.editFormRef.validate(async (valid)=>{
        if(!valid) return;
        const { data: res } = await this.$http.put(`roles/${this.editForm.id}`,this.editForm);
        if( res.meta.status == 200 )
        {
          this.editDialogVisible=false;
          this.$message.success('修改成功！');
          this.getRoleList();
        }
        else
        {
          this.$message.error('修改失败！');
        }
      });      
    },
    async deleteRole(role) {
      const result = await this.$confirm(`确定要删除用户：${role.roleName}？`,'确认',{
        type: 'warning'
      }).catch(err=>err);
      if(result=='confirm') {
        console.log('删除')
        const { data: res } = await this.$http.delete(`roles/${role.id}`);
        if( res.meta.status == 200 )
        {
          this.$message.success('删除成功！');
          this.getRoleList();
        }
        else
        {
          this.$message.error('删除失败！');
        }
      }
    },
    // 弹窗确认是否删除权限
    async removeRightById(role,rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除此权限，确认吗？','提示',{
        confirmText: '确定',
        cancelText: '取消',
        type: 'warning'
      }).catch(err=>err);
      if(confirmResult!='confirm') return this.$message.info('取消删除！');
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`);
      if(res.meta.status!=200) {
        return this.$message.error('删除权限失败！');
      }
      role.children=res.data;
      console.log('确认删除！');
    },
    // 弹窗设置角色权限
    async showSetRightDialog(role) {
      // 设定当前角色id
      this.curRoleId=role.id;
      // 获取所有权限的数据
      const { data: res} = await this.$http.get('rights/tree');
      if(res.meta.status!=200) {
        return this.$message.error('获取所有权限失败！');
      }
      this.rightList=res.data;
      console.log(res.data);
      this.defaultCheckedKeys=[];
      if(role.children)
        this.getLeafKeys(role.children,this.defaultCheckedKeys);
      this.setRightDialogVisible=true;
    },
    //选中当前角色对应的right
    getLeafKeys(nodes,list) {
        for(var i=0;i<nodes.length;i++) {
          if(nodes[i].children)
            this.getLeafKeys(nodes[i].children,list);
          else
            list.push(nodes[i].id);
      }
    },
    async setRoleRightList() {
      // 获取所有选中和半选中节点的id
      var keys=[].concat(this.$refs.treeRef.getCheckedKeys()).concat(this.$refs.treeRef.getHalfCheckedKeys());
      console.log(keys);
      const rids=keys.join(',');
      const { data: res } = await this.$http.post(`roles/${this.curRoleId}/rights`,{rids:rids});
      if(res.meta.status!=200) {
        return this.$message.error('保存角色权限列表失败！');
      }
      this.getRoleList();
      this.$message.success('保存角色权限列表成功！');
      this.setRightDialogVisible=false;
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 8px;
}
.bd-top {
  border-top: 1px solid #eee;
}
.bd-bottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>